﻿#pragma once
#include <QWidget>
#include <QVBoxLayout>
#include <QListWidget>
#include <QLabel>
#include <QPushButton>
#include <QFontDatabase>
#include <QScrollBar>
#include <QMouseEvent>
#include <QApplication>
#include <QDebug>
#include <QTimer>
#include <QPainter>
#include <QComboBox>
#include <QLineEdit>
#include <QHBoxLayout>

class FontScrollWidget : public QWidget
{
    Q_OBJECT

public:
    explicit FontScrollWidget(QWidget* parent = nullptr);
    ~FontScrollWidget();

    QString selectedFont() const { return m_listWidget->currentItem() ? m_listWidget->currentItem()->text() : ""; }
    void scrollToFont(const QFont& font);
signals:
    void fontChanged(const QFont& font);
    void hidden();

protected:
    void paintEvent(QPaintEvent* event) override;
    void resizeEvent(QResizeEvent* event) override;
    void mousePressEvent(QMouseEvent* event) override;
    void mouseMoveEvent(QMouseEvent* event) override;
    void mouseReleaseEvent(QMouseEvent* event) override;
    void closeEvent(QCloseEvent* event) override;

private slots:
    void onItemClicked(QListWidgetItem* item);
    void onCloseButtonClicked();
    void onScrollValueChanged(int value);
    void loadVisibleFonts();
    void onSearchTextChanged(const QString& text);
    void onClearSearchClicked();

private:
    void snapToParentEdge();
    void initializeFontList();
    void applyFontToItem(QListWidgetItem* item);
    void updateFontList();
    void adjustWidgetHeight();

    int binarySearchFont(const QString& fontFamily);  // 二分查找列表中对应字体O(n -> Log n)

    QListWidget* m_listWidget;
    QTimer* m_hideTimer;
    QTimer* m_loadTimer;  // 延迟加载计时器
    QLineEdit* m_searchEdit; // 搜索输入框
    QPushButton* m_clearSearchButton; // 清除搜索按钮

    // 字体数据
    QStringList m_fontFamilies;
    QStringList m_filteredFontFamilies; // 过滤后的字体列表
    QSet<QString> m_loadedFonts;  // 记录已加载的字体

    // 标题栏相关
    QRect m_titleBarRect;
    const int m_titleBarHeight = 24;
    QPushButton* m_closeButton;

    // 搜索栏相关
    const int m_searchBarHeight = 45;

    // 拖拽相关
    QPoint m_dragStartPos;
    bool m_isDragging;
    const int m_snapDistance = 8;

    // 边距设置
    const int m_windowMargin = 10;  // 窗口四周边距
    const int m_contentMargin = 6; // 内容区域边距
};